import React, { useEffect, useRef, forwardRef, useImperativeHandle } from 'react';

function randomText(length = 4) {
  const chars = '1234567890ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz';
  let text = '';
  for (let i = 0; i < length; i++) {
    text += chars[Math.floor(Math.random() * chars.length)];
  }
  return text;
}

const CaptchaCanvas = forwardRef(({ onChange }, ref) => {
  const canvasRef = useRef(null);
  const textRef = useRef('');

  // 绘制验证码
  const draw = () => {
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    canvas.width = 98;
    canvas.height = 45;
    ctx.fillStyle = '#FFD600';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 生成验证码
    const text = randomText();
    textRef.current = text;
    if (onChange) onChange(text);

    ctx.font = '25px Microsoft YaHei';
    ctx.fillStyle = '#222';
    for (let i = 0; i < text.length; i++) {
      ctx.fillText(text[i], 18 * i + 10, 30 + Math.random() * 8);
    }

    // 干扰线
    for (let i = 0; i < 2; i++) {
      ctx.beginPath();
      ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.strokeStyle = 'rgba(50,50,50,0.3)';
      ctx.lineWidth = 0.5;
      ctx.stroke();
    }
    // 干扰点
    for (let i = 0; i < 20; i++) {
      ctx.beginPath();
      const px = Math.random() * canvas.width;
      const py = Math.random() * canvas.height;
      ctx.arc(px, py, 1, 0, 2 * Math.PI);
      ctx.fillStyle = 'rgba(50,50,50,0.3)';
      ctx.fill();
    }
  };

  useEffect(() => {
    draw();
    // eslint-disable-next-line
  }, []);

  // 刷新验证码
  const refresh = () => {
    draw();
  };

  // 暴露refresh方法给父组件
  useImperativeHandle(ref, () => ({
    refresh
  }));

  return (
    <canvas
      ref={canvasRef}
      width={98}
      height={45}
      className="rounded border border-gray-200 cursor-pointer"
      title="点击刷新验证码"
      onClick={refresh}
      style={{ display: 'block' }}
    />
  );
});

export default CaptchaCanvas; 